import os
from werkzeug.utils import secure_filename
from flask import Blueprint, current_app, render_template, request, redirect  # 导入蓝图模块
from fun import *
from exts import db
import jwt
import datetime
from models import DNew,DCategory
from forms import TestForm
index_index = Blueprint('index',__name__,url_prefix='/index')

@index_index.route('/')
def index():
    info = DNew.query.filter(DNew.status == 0).order_by(DNew.id.desc()).first()
    cate=DCategory.query.filter(DCategory.id == info.cid).first()
    list = DNew.query.filter(DNew.status == 0).order_by(DNew.view.desc()).limit(5).all()
    return render_template('index/index/index.html',info=info,cate_name=cate.name,list=list)

@index_index.route('/list')
@index_index.route('/list/<int:id>')   #默认第一页
@index_index.route('/list/<int:id>/<int:page>')
def list(id=None,page=1):
    if id == None:
        id = request.args.get('id', '0')
        page = int(request.args.get('page', '1'))

    info = DCategory.query.filter(DCategory.id == id).first()
    if info==None :
        return render_template('404.html')
    pn = DNew.query.filter(DNew.cid == id).filter(DNew.status == 0).order_by(DNew.id.desc()).paginate(page=page, per_page=5)

    data={
        'name':info.name,
        'pn':pn,
        'id':id
    }
    return render_template('index/index/list.html',**data)


# @index_index.route('/show')
# def show():
#     id = request.args.get('id', '0')
#     info = DNew.query.filter(DNew.id == id).first()  # 返回模型对象/None
#     DNew.query.filter(DNew.id == id).update({'view': info.view+1})
#     db.session.commit()
#     return render_template('index/index/show.html',info=info)

@index_index.route('/show')
@index_index.route('/show/<int:id>')
def show(id=None):
    if id == None:
        id = request.args.get('id', '0')
    info = DNew.query.filter(DNew.id == id).first()
    if info==None :
        return render_template('404.html')
    DNew.query.filter(DNew.id == id).update({'view': info.view+1})
    db.session.commit()
    return render_template('index/index/show.html',info=info)

@index_index.route('/add',methods=['GET','POST'])
def add():
    if request.method=='GET':
        return render_template('index/index/add.html')
    else:

        form = TestForm(request.form)
        if not form.validate(): #如果验证通过，则 函数返回 True ，否则返回 False
            # 表单验证不通过，获取错误信息
            errors = {}
            for field, errors in form.errors.items():
                print(field, errors)
                #errors[field] = errors  # 你可以根据需要修改这里的逻辑来存储错误信息
            # 在这里，你可以将错误信息传递给模板进行渲染，或者进行其他处理
            return "<script>alert('发表失败!');window.history.back()</script>"
        data=request.form.to_dict()
        new = DNew(**data)  # 创建对象及内容
        db.session.add(new)  # 添加
        db.session.commit()  # 提交
        return "<script>alert('发布成功!');location.href='/'</script>"

@index_index.route('/jwt')  #产生token
@index_index.route('/jwt_login')
def jwt_login():
    app = current_app._get_current_object()
    # 设置载荷信息
    payload = {
        "userid": 888,
        # 过期时间要用0时区的。
        "exp": datetime.datetime.utcnow() + datetime.timedelta(days=1)
    }

    # 加密并获取token
    token = jwt.encode(payload, key=app.config['SECRET_KEY'], algorithm="HS256")
    print(token)
    a=jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
    print(a)
    #return "token: %s" % token
    return render_template('index/index/token.html',token=token)
@index_index.route('/jwt_check',methods=['GET','POST'])  #验证token
def jwt_check():
    print('开始校验token')
    app = current_app._get_current_object()
    print(request.headers.get("Authorization"))


    try:
        jwt_decode = jwt.decode(request.headers.get("Authorization"), key=app.config['SECRET_KEY'], algorithms=["HS256"])

        print(jwt_decode.get("userid"))

        return jwt_decode
    except Exception as e:
        print(e)
        return "token校验出错！"

@index_index.route('/form')       #上传表单
def form():
    return render_template('index/index/form.html')
@index_index.route('/upload',methods=['POST'])       # /admin/index/
def upload():
    if 'file' not in request.files:
        print('无文件部分')
        return ''

    file = request.files['file']
    if file.filename == '':
        print('没有选择文件')
        return ''

    if file:
        app = current_app._get_current_object()
        if file and allowed_file(file.filename,app.config['ALLOWED_EXTENSIONS']):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return f'文件上传成功: {filename}'
        else:
            print("文件类型不正确")
            return ''
